#!/bin/bash
# Simplified Repository Commit Tool - Only for Demo repository
# This script now only handles commits for the demo root repository

# =============================================
# Configuration
# =============================================

# Set working directory
if [ -z "$AWS" ]; then
    if [ -n "$HOME" ]; then
        export AWS="$HOME/workspace"
    else
        export AWS="C:/Users/Administrator/workspace"
    fi
fi

# Only process the demo repository (D)
DEMO_REPO_PATH="$AWS/demo"

# README.md file path
TOPIC_FILE="$AWS/demo/matrix_html/README.md"

# =============================================
# Utility Functions
# =============================================

echo_info() {
    echo "[INFO] $1"
}

echo_error() {
    echo "[ERROR] $1" >&2
}

# =============================================
# Commit Function
# =============================================

# Commit the demo repository
commit_demo_repo() {
    local commit_content="$1"
    
    # Validate repository path
    if [ ! -d "$DEMO_REPO_PATH" ]; then
        echo_error "Directory not found: $DEMO_REPO_PATH"
        return 1
    fi
    
    if [ ! -d "$DEMO_REPO_PATH/.git" ]; then
        echo_error ".git directory not found in: $DEMO_REPO_PATH"
        return 1
    fi
    
    # Change to repository directory
    cd "$DEMO_REPO_PATH" || {
        echo_error "Failed to change directory: $DEMO_REPO_PATH"
        return 1
    }
    
    # Check Git availability
    if ! command -v git &>/dev/null; then
        echo_error "Git command not found"
        return 1
    fi
    
    # Fetch latest from origin to check for updates
    git fetch origin || {
        echo_error "Failed to fetch latest updates from origin"
        return 1
    }
    
    # Check if there are remote updates (commits on origin not on local)
    local remote_updates=0
    remote_updates=$(git log --oneline HEAD..origin/$(git rev-parse --abbrev-ref HEAD) 2>/dev/null | wc -l | tr -d ' ')
    
    if [ "$remote_updates" -gt 0 ]; then
        echo_info "Detected $remote_updates new commits on origin, preparing to synchronize..."
        
        # Check if there are local unpushed commits
        local unpushed_count=0
        unpushed_count=$(git log --oneline origin/$(git rev-parse --abbrev-ref HEAD)..HEAD 2>/dev/null | wc -l | tr -d ' ')
        
        if [ "$unpushed_count" -gt 0 ]; then
            echo_info "Soft resetting $unpushed_count local unpushed commits to sync with origin..."
            git reset --soft HEAD~$unpushed_count || {
                echo_error "Failed to soft reset local unpushed commits"
                return 1
            }
        fi
        
        # Stash all changes (staged and unstaged) before pulling updates
        echo_info "Stashing all changes before pulling updates..."
        git stash push -a -m "temp stash before pull" || {
            echo_error "Failed to stash all changes"
            return 1
        }
        
        # Pull the latest changes from origin
        echo_info "Pulling latest changes from origin..."
        git pull origin "$(git rev-parse --abbrev-ref HEAD)" || {
            echo_error "Failed to pull latest changes from origin"
            return 1
        }
        
        # Restore the stashed changes
        echo_info "Restoring stashed changes..."
        if ! git stash pop; then
            echo_error "Failed to restore stashed changes due to conflicts"
            echo_error "Please manually resolve the conflicts and then continue"
            return 1
        fi
    fi
    
    # Add all changes
    git add .
    
    # Check if there are any changes to commit (staged, unstaged, or untracked)
    local has_changes=false
    
    # Check for staged changes
    if ! git diff --cached --quiet; then
        has_changes=true
    fi
    
    # Check for unstaged changes
    if ! git diff --quiet; then
        has_changes=true
    fi
    
    # Check for untracked files
    if [ -n "$(git ls-files --others --exclude-standard)" ]; then
        has_changes=true
    fi
    
    # If no changes detected, skip commit
    if [ "$has_changes" = false ]; then
        echo_info "No changes detected, skipping commit"
        return 0
    fi
    
    # Check if there are unpushed commits
    local unpushed_count=0
    if command -v git &>/dev/null; then
        unpushed_count=$(git log --oneline origin/$(git rev-parse --abbrev-ref HEAD)..HEAD 2>/dev/null | wc -l | tr -d ' ')
    fi
    
    # Create commit or amend last commit based on unpushed status
    if [ "$unpushed_count" -gt 0 ]; then
        echo_info "Detected $unpushed_count unpushed commits, amending last commit with new message"
        git commit --amend -m "$commit_content"
    else
        # Create regular commit (without --allow-empty since we checked for changes)
        git commit -m "$commit_content"
    fi

    echo_info "Successfully committed demo repository"
    return 0
}

# =============================================
# Main Function
# =============================================

main() {
    local commit_content=""
    
    # If arguments are provided, use them as commit content
    if [ $# -gt 0 ]; then
        commit_content="$*"
        echo_info "Using commit content from command line: $commit_content"
    else
        # Fallback to README.md if no arguments provided
        echo_info "No command line arguments provided, reading from README.md"
        
        # Check if README.md exists and is readable
        if [ ! -f "$TOPIC_FILE" ]; then
            echo_error "README.md file not found: $TOPIC_FILE"
            echo "Usage: $0 [commit-message]"
            return 1
        fi
        
        # Read first line from README.md
        commit_content="$(head -n 1 "$TOPIC_FILE" 2>/dev/null || echo '')"
        
        # Check if content was read successfully
        if [ -z "$commit_content" ]; then
            echo_error "README.md is empty or unreadable"
            return 1
        fi
    fi
    
    # Trim any leading/trailing whitespace
    commit_content="$(echo "$commit_content" | sed 's/^[ 	]*//;s/[ 	]*$//')"
    
    # Generate formatted commit message with date, weekday, timestamp (hour:minute) and content
    # Format: MMDD/weekday/HHMM [content]
    local date_str=$(date +"%m%d")
    local weekday=$(date +"%u")  # 1-7 (Monday-Sunday)
    local timestamp=$(date +"%H%M")
    local formatted_content="$date_str/$weekday/$timestamp $commit_content"
    
    echo_info "Formatted commit content: $formatted_content"
    
    # Commit demo repository
    echo_info "Committing demo repository..."
    commit_demo_repo "$formatted_content"
    
    local result=$?
    if [ $result -eq 0 ]; then
        echo ""
        echo "✅ Repository commit process completed successfully!"
        echo ""
    else
        echo ""
        echo "❌ Repository commit process failed with errors!"
        echo ""
    fi
    
    return $result
}

# Call main function with all provided arguments
main "$@"